'''
Author: mypx
Date: 2025-10-21 15:29:06
LastEditTime: 2025-10-21 15:32:31
LastEditors: mypx mypx_coder@163.com
Description: 
'''
# 选择组模块
from PyQt6.QtWidgets import QWidget, QGroupBox, QVBoxLayout, QRadioButton, QButtonGroup, QSizePolicy
from PyQt6.QtCore import Qt
from typing import Dict, Optional
from ..base_modules.prompt_module import PromptModule
from parser.config_model import ChoiceItem, ConfigItem


class ChoiceModule:
    """选择组模块"""

    def __init__(self):
        self.prompt_module = PromptModule()
        self.choice_groups: Dict[str, QGroupBox] = {}
        self.button_groups: Dict[str, QButtonGroup] = {}
        self.radio_buttons: Dict[str, Dict[str, QRadioButton]] = (
            {}
        )  # {choice_id: {config_id: QRadioButton}}

    def create_choice_group(
        self, choice_item: ChoiceItem, parent: Optional[WIDGET] = None
    ) -> QWidget:
        """创建选择组"""
        group_box = QGroupBox(choice_item.prompt or "Choice", parent)
        group_box.setObjectName(f"choice-group-{choice_item.id}")
        # 通过样式为标题预留空间，避免标题与首个单选项或下一个控件重叠
        group_box.setStyleSheet(
            """
            QGroupBox { padding-top: 24px; font-weight: bold; }
            QGroupBox::title { subcontrol-origin: margin; subcontrol-position: top left; padding: 0 6px; }
            """
        )
        group_box.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)

        layout = QVBoxLayout(group_box)
        layout.setContentsMargins(10, 8, 10, 10)
        layout.setSpacing(8)

        button_group = QButtonGroup(group_box)
        button_group.setExclusive(not choice_item.optional)

        self.button_groups[choice_item.id] = button_group
        self.radio_buttons[choice_item.id] = {}

        # 添加选项
        for config_item in choice_item.children:
            radio_button = QRadioButton(
                config_item.properties.prompt or config_item.name
            )
            radio_button.setObjectName(f"choice-radio-{config_item.id}")
            # 不使用 setData，Qt 原生控件无该方法；使用外部字典跟踪

            if config_item.id == choice_item.selected_item:
                radio_button.setChecked(True)

            button_group.addButton(radio_button)
            layout.addWidget(radio_button)

            self.radio_buttons[choice_item.id][config_item.id] = radio_button

        # 如果允许不选，添加一个空选项
        if choice_item.optional:
            empty_radio = QRadioButton("(None)")
            empty_radio.setObjectName(f"choice-radio-none-{choice_item.id}")

            if choice_item.selected_item is None:
                empty_radio.setChecked(True)

            button_group.addButton(empty_radio)
            layout.addWidget(empty_radio)

        self.choice_groups[choice_item.id] = group_box
        return group_box

    def update_choice_selection(
        self, choice_id: str, selected_item_id: Optional[str]
    ) -> None:
        """更新选择组的选中状态"""
        radio_buttons = self.radio_buttons.get(choice_id)
        if not radio_buttons:
            return

        # 清除所有选中状态
        for radio in radio_buttons.values():
            radio.setChecked(False)

        # 设置新的选中状态
        if selected_item_id in radio_buttons:
            radio_buttons[selected_item_id].setChecked(True)
        elif selected_item_id is None and f"choice-radio-none-{choice_id}" in [
            radio.objectName() for radio in radio_buttons.values()
        ]:
            # 选中空选项
            for radio in radio_buttons.values():
                if radio.objectName() == f"choice-radio-none-{choice_id}":
                    radio.setChecked(True)
                    break

    def update_choice_visibility(self, choice_id: str, visible: bool) -> None:
        """更新选择组可见性"""
        group_box = self.choice_groups.get(choice_id)
        if group_box:
            group_box.setVisible(visible)
